package 算法思维系列;

import java.util.HashMap;
import java.util.Map;

public class 两数之和_1 {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        //记录元素值到索引的映射
        Map<Integer, Integer> index = new HashMap<>();

        for (int i = 0; i < n; i++) {
            index.put(nums[i], i);
        }

        for (int i = 0; i < n; i++) {
            int other = target - nums[i];
            //如果other在index中，并且不是nums[i]本身，就证明有满足条件的元素
            if (index.containsKey(other) && index.get(other) != i) {
                return new int[]{i, index.get(other)};
            }
        }
        return new int[]{-1, -1};
    }
}
